package com.lcm.weam.shiro;

import com.lcm.weam.entity.resp.ProfileResult;
import com.lcm.weam.entity.sys.Permission;
import com.lcm.weam.entity.sys.Role;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.ArrayList;
import java.util.List;

/**
 * 基础realm，用于鉴权，认证交给子类继承重写
 */
public class BaseRealm extends AuthorizingRealm {


    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        return null;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //授权方法
        ProfileResult profileResult = (ProfileResult)principals.getPrimaryPrincipal();
        //构造权限字符数组列表
        Role role = profileResult.getRole();
        List<String> stringPermissions = new ArrayList<>();
        for (Permission permission : role.getPermissions()){
            stringPermissions.add(permission.getPname());
        }
        //构造AuthorizationInfo
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRole(role.getRname());
        info.addStringPermissions(stringPermissions);
        return info;
    }
}
